var ifSuperMan = window.localStorage.getItem("backstage-access-ifSuperMan");
var webSiteId = ly.getUrlParam("webSiteId");
var urlType = ly.getUrlParam("type");
var workDaySettingList = [];

$(function() {
  /**
   * 判断超级管理员
   * 1 超级管理员 隐藏设置-保存按钮
   * 0 普通管理员 显示设置-保存按钮
   */
  /* if (ifSuperMan == 1) {
    $("#save-btn").hide();
  }
  else {
    $("#save-btn").show();
  } */
  request({
    url: site.apiUrl + "/orderSetting/getOrderSettingInfo",
    type: "get",
    data: {
      workDay: getDateNow(),
      webId: webSiteId
    },
    callback: function(f) {
      if (f.code == 200) {
        var data = f.data;
        var dateData = data.workList; // 日期
        if (dateData && dateData.length !== 0) {
          var workDayStr = '';
          for(var i = 0; i < dateData.length; i++) {
            workDayStr += dateData[i].workDay + ',';
          }
          $("#orderTime").val(workDayStr.substr(0, workDayStr.length-1));
        } else {
          $("#orderTime").val('');
        }

        var timeData = data.list;  // 时间段
        if (timeData && timeData.length !== 0) {
          for(var i = 0; i < timeData.length; i++) {
            // workDayStr += timeData[i].workDay + ',';
            $(".time_list").append('<li><input type="hidden" value="'+ timeData[i].id +'"><input type="text" class="ipt lay_time" placeholder="请选择时间范围" value="'+ timeData[i].startTime + " - " + timeData[i].endTime +'"><input type="text" class="ipt sort" placeholder="预约名额" value="'+ timeData[i].orderNum +'"> 人<a class="button_a" onclick="addItem()" title="新增"><i class="iconfont icon-add"></i></a><a class="button_a" onclick="delItem(this)" title="删除"><i class="iconfont icon-shanchuguanbicha"></i></a></li>');
          }
          // $("#orderTime").val(workDayStr.substr(0, workDayStr.length-1));
        } else {
          $(".time_list").html('<li><input type="text" class="ipt lay_time" placeholder="请选择时间范围"><input type="text" class="ipt sort" placeholder="预约名额"> 人<a class="button_a" onclick="addItem()" title="新增"><i class="iconfont icon-add"></i></a><a class="button_a" onclick="delItem(this)" title="删除"><i class="iconfont icon-shanchuguanbicha"></i></a></li>');
        }
        timeInit();
      } else {
        ly.toast(f.desc || f.msg);
      }
    }
  })

  timeInit();
  $('.whiteboard').remove();
  
  //提交
  $("body").on("click", "#save-btn", function(event) {
    event.preventDefault();
    var orderTime = $("#orderTime").val();
    if (orderTime !== '') {
      submitFom();
    } else {
      ly.toast('请设置工作日！');
    }
  })

});

// 初始化时间段选择
function timeInit () {
  lay('.lay_time').each(function(){
    laydate.render({
      elem: this,
      trigger: 'click',
      type: 'time',
      format: 'HH:mm',
      range: true
    });
  });
}

// 日期转换
function getDateNow() {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  if (day >= 0 && day <= 9) {
    day = '0' + day;
  }
  let currentdate = year + '-' + month + '-' + day;
  return currentdate;
}

// 添加时间范围
function addItem() {
  var itemHtml = '';
      itemHtml += '<li>'
      itemHtml += '<input type="text" class="ipt lay_time" placeholder="请选择时间范围">'
      itemHtml += '<input type="text" class="ipt sort" placeholder="预约名额"> 人'
      itemHtml += '<a class="button_a" onclick="addItem()" title="新增"><i class="iconfont icon-add"></i></a>'
      itemHtml += '<a class="button_a" onclick="delItem(this)" title="删除"><i class="iconfont icon-shanchuguanbicha"></i></a>'
      itemHtml += '</li>'
  $(".time_list").append(itemHtml);
  
  lay('.lay_time').each(function(){
    laydate.render({
      elem: this,
      trigger: 'click',
      type: 'time',
      format: 'HH:mm',
      range: true
    });
  });
}
// 删除时间范围
function delItem(that) {
  var $li = $(".time_list li");
  if ($li.length === 1) {
    ly.toast('至少保留一项！');
  } else {
    $(that).parent().remove();
  }
}

// 获取时间范围集合
function getWorkDaySettingList() {
  workDaySettingList = [];
  var dateData = $("#orderTime").val().replace(/\s*/g,"");
  var $li = $(".time_list li");
  $li.each(function(){
    if ($(this).find('input[type=hidden]').length !== 0) {
      workDaySettingList.push({
        id: $(this).find('input[type=hidden]').val(),
        webId: webSiteId,
        workDay: dateData,
        startTime: $(this).find('input.lay_time').val().split(' - ')[0],
        endTime: $(this).find('input.lay_time').val().split(' - ')[1],
        orderNum: $(this).find('input.sort').val()
      });
    } else {
      workDaySettingList.push({
        webId: webSiteId,
        workDay: dateData,
        startTime: $(this).find('input.lay_time').val().split(' - ')[0],
        endTime: $(this).find('input.lay_time').val().split(' - ')[1],
        orderNum: $(this).find('input.sort').val()
      });
    }
  });
  return workDaySettingList;
}

/*
 * 提交表单
 */
function submitFom() {
  var url = site.apiUrl + "/orderSetting/addOrderSetting";

  console.log(JSON.stringify(getWorkDaySettingList()))

  request({
    url: url,
    data: getWorkDaySettingList(),
    type: "post",
    ajaxform: "true",
    callback: function(f) {
      if (f.code == 200) {
        ly.alert('设置成功', function() {
          window.location.reload();
        });
      } else {
        ly.toast(f.msg);
      }
    }
  });
}
